package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IPublishService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Service
public class PublishServiceImpl implements IPublishService {
    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService apArticleService;

    @Autowired
    private Configuration configuration;

    /**
     * 生成静态页面
     *
     * @param article
     * @param content
     */
    @Async
    @Override
    public void createHtml(ApArticle article, String content) {
        //使用freemarker生成html文件
        //获取模板
        try {
            Template template = configuration.getTemplate("article.ftl");

            //准备数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //合并模板和数据
            Writer writer = new StringWriter();
            template.process(map, writer);

            //将文件存到minio表中
            String name = article.getId() + ".html";
            //构建输入流
            InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload(name, is, "text/html");
            //将minion返回的地址保存到文章表中
            article.setStaticUrl(url);
            apArticleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
